package com.fanshuai.stack;

public class LinkedStack<E> implements Stack<E> {
    class Node<E> {
        E data;
        Node<E> next;
        Node<E> pre;

        Node(E data) {
            this.data = data;
            this.next = null;
            this.pre = null;
        }

        Node() {
            this.data = null;
            this.next = null;
            this.pre = null;
        }
    }

    private Node<E> top;
    private int size;

    public LinkedStack() {
        top = new Node<E>();
        size = 0;
    }

    @Override
    public int size() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public void push(E e) {
        Node<E> node = new Node<>(e);

        Node<E> next = top.next;
        node.next = next;
        if (null != next) {
            next.pre = node;
        }

        top.next = node;
        node.pre = top;
        size++;
    }

    @Override
    public E pop() {
        if (size <= 0) {
            throw new IndexOutOfBoundsException("stack empty");
        }

        Node<E> node = top.next;
        top.next = node.next;
        if (node.next != null) {
            node.next.pre = top;
        }

        E data = node.data;
        node.pre = null;
        node.next = null;
        node.data = null;
        size--;

        return data;
    }

    @Override
    public E peek() {
        if (size <= 0) {
            throw new IndexOutOfBoundsException("stack empty");
        }

        Node<E> node = top.next;
        return node.data;
    }
}
